<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


//机器人检测
function is_bot()
{
	$spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
	$browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
	if (preg_match("/($browsers)/i", $_SERVER['HTTP_USER_AGENT']))
	{
		return false;
	}
	elseif(preg_match("/($spiders)/i", $_SERVER['HTTP_USER_AGENT']))
	{
		return true;
	}
	return false;
}


//词语过滤
function censor_text($text)
{
    $words = F('cache_censored_words');
	return !empty($words) ? preg_replace($words['search'], $words['replace'], $text) : $text;
}


//检查是否需要验证码(true=>'需要',false=>'不需要')
function require_captcha_when($type, $group=6)
{
    $group = !empty($group) ? intval($group) : 6;
	$captcha = unserialize(get_site_config('captcha_when'));
	$groups = explode(',', get_site_config('group_without_captcha'));
	if (in_array($group, $groups))
	{
		return false;
	}
	return empty($captcha[$type]) ? false : true;
}


//检查一天活动限制('ture' => '超出', 'false' => '未超出')
function exceed_activity_limit($user_id, $user_group, $type)
{
	$Activity = M('Activity');
	$group = F('cache_usergroup_'.$user_group);
	switch (strtolower($type))
	{
	  	case 'question':
	  		$max = $group['max_questions_per_day'];
	  		break;
	  	case 'answer':
	  		$max = $group['max_answers_per_day'];
	  		break;
	  	case 'comment':
	  		$max = $group['max_comments_per_day'];
	  		break;
	  	case 'vote':
	  		$max = $group['max_votes_per_day'];
	  		break;
	  	case 'rate':
	  		$max =$group['max_rates_per_day'];
	  		break;
	  	case 'star':
	  		$max = $group['max_stars_per_day'];
	  	case 'email':
	  	    $max = $group['max_emails_per_day'];
			break;
	}
	$start = strtotime(date('Y-m-d'));
	$end = $start + 86400;
	$map = array(
	   'user_id' => intval($user_id),
	   'type' => $type,
	   'create_time' => array('between', array($start, $end)),
	);
	$count = $Activity->where($map)->count();
	if ($max && $count > $max)
	{
		return true;
	}
	return false;
}


//检查关注限制('ture' => '超出', 'false' => '未超出')
function exceed_follow_limit($user_id, $user_group, $type)
{
	$Follow = M('UserFollow');
	$group = F('cache_usergroup_'.$user_group);
	$max = intval($group['max_contact']);
	$map = array(
	   'source_user' => $user_id,
	   'status' => 1,
	);
	$count = $Follow->where($map)->count();
	if ($max && $count > $max)
	{
		return true;
	}
	return false;
}


//检查链接限制('ture' => '超出', 'false' => '未超出')
function exceed_link_limit($str)
{
    $limit = intval(get_site_config('max_post_links'));
    preg_match_all("/(http|ftp):\/\//", $str, $matchs);
    if ($limit > 0 && count($matchs[0]) > $limit)
    {
    	return true;
    }
    return false;
}


//人性化时间格式
function pretty_date($time, $type='past')
{
	if ('past' == $type || $time < time())
	{
		$diff = time() - $time;
	}
	elseif('future' == $type || $time > time())
	{
		$diff = $time - time();
	}
    $seconds = max($diff, 1);
	$scales = array(
		31536000 => array('1_year', 'x_years'),
		 2592000 => array('1_month', 'x_months'),
		  604800 => array('1_week', 'x_weeks'),
		   86400 => array('1_day', 'x_days'),
		    3600 => array('1_hour', 'x_hours'),
		      60 => array('1_minute', 'x_minutes'),
		       1 => array('1_second', 'x_seconds'),
	);
	foreach ($scales as $scale => $phrases)
	{
		if ($seconds >= $scale)
		{
			$count = floor($seconds/$scale);
			$str = (1 == $count) ? L($phrases[0]) : sprintf(L($phrases[1]), $count);
			break;
		}
	}
	return ($type == 'past') ? sprintf(L('x_ago'), $str) : sprintf(L('x_left'), $str);
}


//tags字符处理
function filter_tags($tags)
{
	$tag_array = array();
	$tags = str_replace(array(chr(0xa3).chr(0xac), chr(0xa1).chr(0x41), chr(0xef).chr(0xbc).chr(0x8c)), ',', $tags);
	if(false !== strpos($tags, ','))
	{
		$tag_array = array_unique(explode(',', $tags));
	}
	else
	{
		$tags = str_replace(array(chr(0xa1).chr(0xa1), chr(0xa1).chr(0x40), chr(0xe3).chr(0x80).chr(0x80)), ' ', $tags);
		$tag_array = array_unique(explode(' ', $tags));
	}
	return $tag_array;
}


//句末自动添加问号
function auto_question_mark($str, $force=1)
{
	$str = trim($str);
	if ($force && '?' != substr($str, -1, 1))
	{
		$str .= ' ? ';
	}
	return $str;
}


//高亮搜索关键字
function highlight_keyword($str, $keyword)
{
	$str_array = explode('-', format_title($str, '-'));
	$keyword_array = explode('-', format_title($keyword, '-'));
	foreach ($str_array as $key => $value)
	{
		if (in_array(strtolower($value), $keyword_array))
		{
			$str_array[$key] = '<span class="highlight">'. $value .'</span>';
		}
	}
	return implode(' ', $str_array) .' ? ';
}


//获取某周某天的时间戳,以本周为基准,$week(0=>本周,-1=>上周,1=>下周),$day(范围1-7)表示第1-7天
function get_week_day_time($week=0, $day=1)
{
	$stamp_today = strtotime(date('Y-m-d'));
	$week_today  = date('N');
	$stamp_week_day = $stamp_today + (7 * $week + $day - $week_today) * 86400;	
	return $stamp_week_day;		
}


//获取百分比
function get_percentage($smaller, $bigger)
{
	if (!$smaller || !$bigger) return '0.00';
	return sprintf("%01.2f", 100 * round($smaller/$bigger, 4));
}


//获取问题状态
function get_question_status($status)
{
	$options = L('question_status_options');
	return $options[$status];
}


//取得用户头像
function get_avatar($email, $size=48, $default='', $rating='')
{
    $parameter = unserialize(get_site_config('gravatar_parameters'));
	if (empty($default))
	{
		$custom_default = $parameter['custom_default'];
		$default = $parameter['default'];
		$default = !empty($custom_default) ? urlencode($custom_default) : $default;
	}
	if (empty($rating))
	{
		$rating = $parameter['rating'];
	}
	$hash = md5(strtolower(trim($email)));
	$avatar = 'http://www.gravatar.com/avatar/' .$hash. '?s='. $size .'&r='. $rating .'&d='. $default;
	return $avatar;
}


//取得团队logo
function get_team_logo($team_id)
{
	$Team = M('Team');
	$map = array('team_id'=>$team_id);
	$logo = $Team->where($map)->getField('logo');
	return $logo;	
}


//获取勋章申请条件
function get_medal_permission($str)
{
    $search = array('point_count','question_count','answer_count','best_answer_count','comment_count','follower_count','register_date','and','or');
    $replace = array(L('user_point_count'),L('user_question_count'),L('user_answer_count'),L('user_best_answer_count'),L('user_comment_count'),L('user_follower_count'),L('user_register_date'),L('and'),L('or'));
    return str_ireplace($search, $replace, $str);
}


/**
 * 检查是否有管理分类权限,管理员或超级版主有分类全局权限
 *
 * @param integer $user_id
 * @param integer $admin_group
 * @param integer $cate_id
 * @return bool
 */
function is_moderator($user_id, $admin_group, $cate_id)
{
	$result = false;
	if(!$user_id || !$admin_group)
	{
		return false;
	}
	$temp = F('cache_moderators');
	$moderators = isset($temp[$cate_id]) ? $temp[$cate_id] : array();
	if (3 == $admin_group && $moderators)
	{
		foreach ($moderators as $value)
		{
			if ($user_id == $value['user_id'])
			{
				$result = true;
				break;
			}
		}
	}
	if (in_array($admin_group, array(1,2)))
	{
		$result = true;
	}
	return $result;
}



/**
 * 检查moderator是否具有某项操作权限
 *
 * @param integer $admin_group
 * @param string $action 操作名
 * @return bool
 */
function check_moderator_perms($admin_group, $action)
{
	$result = false;
	$group = F('cache_admingroup_'.$admin_group);
	if (isset($group[$action]) && $group[$action])
	{
		$result = true;
	}
	return $result;
}


/**
 * 获取版主管辖分类区域
 *
 * @param integer $user_id
 * @return array 分类ID数组
 */
function get_mod_categories($user_id)
{
	$Model = M('Moderator');
	$categories = array();
	$map = array('user_id' => $user_id);
	$results = $Model->where($map)->select();
	if ($results)
	{
		foreach ($results as $value)
		{
			$categories[] = $value['category_id'];
		}
		$categories = array_unique($categories);
	}
	return $categories;
}


/* End of file function.php */
/* Location: ./App/Common/Home/function.php */